# 自定义用户认证后端，多账号的登陆
import re

from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from itsdangerous import BadData
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

from users.models import User
from . import constants


# 验证链接提取用户信息
def check_verify_email_token(token):
    """
    验证token并提取user
    :param token:序列化前的数据
    :return:user None
    """
    # 创建对象
    s = Serializer(settings.SECRET_KEY, expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    try:
        # 将数据反序列化
        data = s.loads(token)
    except BadData:
        return None
    else:
        # 提取数据
        user_id = data.get('user_id')
        email = data.get('email')
        try:
            # 查询数据
            user = User.objects.get(id=user_id, email=email)
        except User.DoesNotExist:
            return None
        else:
            return user


def generate_verify_email(user):
    """
    生成邮箱激活链接
    :param user:当前登陆的用户
    :return: token邮箱激活链接
    """
    s = Serializer(settings.SECRET_KEY, expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    data = {'user_id': user.id, 'email': user.email}
    token = s.dumps(data).decode()
    verify_url = settings.EMAIL_VERIFY_URL + '?token=' + token
    return verify_url


def get_user_by_account(account):
    """
    通过账号获取用户
    :param account: 用户名或者手机号
    :return: user
    """
    try:
        if re.match(r'^1[3-9]\d{9}', account):
            # username == 手机号
            user = User.objects.get(mobile=account)
        else:
            # username == 用户名
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileBackend(ModelBackend):
    """自定义用户后端"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        重写用户认证方法(authenticate)
        :param request:
        :param username: 用户名或者手机号
        :param password: 密码明文
        :param kwargs: 额外参数
        :return: user
        """
        # 查询用户
        user = get_user_by_account(username)
        # 使用账号查询用户
        if user and user.check_password(password):
            return user
        else:
            return None
        # 如果查询到用户则校验密码是否正确
        # 返回user
